package com.ruoyi.print.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.print.service.IImageSegService;
import com.ruoyi.print.service.IOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 图片上传控制器
 * 
 * @author ruoyi
 * @date 2025-01-20
 */
@RestController
@RequestMapping("/print/upload")
public class ImageUploadController extends BaseController {
    
    @Autowired
    @Qualifier("printOssServiceImpl")
    private IOssService ossService;
    
    @Autowired
    private IImageSegService imageSegService;
    
    /**
     * 上传图片到OSS
     */
    @PreAuthorize("@ss.hasPermi('print:upload:upload')")
    @Log(title = "图片上传", businessType = BusinessType.INSERT)
    @PostMapping("/image")
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return error("请选择要上传的文件");
            }
            
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return error("只能上传图片文件");
            }
            
            // 验证文件大小（限制为10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                return error("文件大小不能超过10MB");
            }
            
            // 上传到OSS
            String imageUrl = ossService.uploadFile(file);
            
            Map<String, Object> result = new HashMap<>();
            result.put("originalUrl", imageUrl);
            result.put("message", "上传成功");
            
            return success(result);
            
        } catch (Exception e) {
            logger.error("图片上传失败", e);
            return error("图片上传失败: " + e.getMessage());
        }
    }
    
    /**
     * 调用阿里云分割API
     */
    @PreAuthorize("@ss.hasPermi('print:upload:upload')")
    @Log(title = "图片分割", businessType = BusinessType.UPDATE)
    @PostMapping("/segment")
    public AjaxResult segmentImage(@RequestParam("imageUrl") String imageUrl) {
        try {
            // 验证图片URL
            if (imageUrl == null || imageUrl.trim().isEmpty()) {
                return error("图片URL不能为空");
            }
            
            // 调用分割API
            String segmentedUrl = imageSegService.segmentImage(imageUrl);
            
            Map<String, Object> result = new HashMap<>();
            result.put("originalUrl", imageUrl);
            result.put("segmentedUrl", segmentedUrl);
            result.put("message", "分割成功");
            
            return success(result);
            
        } catch (Exception e) {
            logger.error("图片分割失败", e);
            return error("图片分割失败: " + e.getMessage());
        }
    }
    
    /**
     * 上传并分割图片（推荐使用）
     */
    @PreAuthorize("@ss.hasPermi('print:upload:upload')")
    @Log(title = "图片上传并分割", businessType = BusinessType.INSERT)
    @PostMapping("/upload-and-segment")
    public AjaxResult uploadAndSegment(@RequestParam("file") MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return error("请选择要上传的文件");
            }
            
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return error("只能上传图片文件");
            }
            
            // 验证文件大小（限制为10MB）
            if (file.getSize() > 10 * 1024 * 1024) {
                return error("文件大小不能超过10MB");
            }
            
            // 上传到OSS
            String originalUrl = ossService.uploadFile(file);
            
            // 调用分割API
            String segmentedUrl = imageSegService.segmentImage(originalUrl);
            // 将通用分割转换为https，需要再次上传
            String httpsSegmentedUrl = null;
            if (segmentedUrl != null) {
                // 下载分割后的图片并上传到OSS
                httpsSegmentedUrl = ossService.uploadFileFromUrl(segmentedUrl);
            }
            Map<String, Object> result = new HashMap<>();
            result.put("originalUrl", originalUrl);
            result.put("segmentedUrl", httpsSegmentedUrl);
            result.put("message", "上传并分割成功");
            
            return success(result);
            
        } catch (Exception e) {
            logger.error("图片上传并分割失败", e);
            return error("图片上传并分割失败: " + e.getMessage());
        }
    }


    
    /**
     * 删除OSS文件
     */
    @PreAuthorize("@ss.hasPermi('print:upload:delete')")
    @Log(title = "删除OSS文件", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete")
    public AjaxResult deleteFile(@RequestParam("url") String url) {
        try {
            boolean success = ossService.deleteFile(url);
            if (success) {
                return success("删除成功");
            } else {
                return error("删除失败");
            }
        } catch (Exception e) {
            logger.error("删除OSS文件失败", e);
            return error("删除失败: " + e.getMessage());
        }
    }
} 